const { Controller } = require("egg");
const path = require("path");
const fs = require("fs");
const { respAdapter } = require("../../utils");

class DataController extends Controller {
  async index() {
    const { ctx, app, config } = this;
    try {
      const token = ctx.headers.authorization
        ? ctx.headers.authorization.split(" ")[1]
        : "";
      await app.jwt.verify(token, config.jwt.secret);
      const { body } = ctx.request;
      console.log("😈body", body);
      let timeWhere;
      if (body.beginTime)
        timeWhere = `WHERE created_time >= '${body.beginTime} 00:00:00'
  AND created_time < '${body.endTime} 00:00:00'`;

      //   分数
      const score = await this.app.mysql.query(`SELECT
      score,
      COUNT(*) AS count 
  FROM
      manager 
  ${timeWhere ? timeWhere : ""}
  GROUP BY
  score ;`);

      //   区划
      const area = await this.app.mysql.query(`SELECT
      area,
      COUNT(*) AS count 
  FROM
      manager 
        ${timeWhere ? timeWhere : ""}
  GROUP BY
      area;`);

      //   经理个数
      const managerNum = await this.app.mysql.query(`SELECT
	COUNT(id) as count
FROM
	manager 
    ${timeWhere ? timeWhere : ""}
`);

      // 物业项目数量
      //     const projectNum = await this.app.mysql.query(`SELECT
      //     MONTH(created_time) AS month,
      //     COUNT(id) AS count
      // FROM
      //     project
      // WHERE
      //     created_time IS NOT NULL
      // GROUP BY
      //     MONTH(created_time);`);

      // 变更数量
      const eventNum = await this.app.mysql.query(`SELECT 
      MONTH(created_time) AS month, 
      COUNT(id) AS count
  FROM 
      event
        ${
          timeWhere
            ? timeWhere
            : `WHERE 
      created_time IS NOT NULL`
        }
  GROUP BY 
      MONTH(created_time);`);

      //   if (!list) {
      //     ctx.body = respAdapter(null, "数据异常，请重试", false);
      //   }

      ctx.body = respAdapter({
        score,
        area,
        managerNum: managerNum?.[0].count || 0,
        // projectNum,
        eventNum
      });
    } catch (err) {
      ctx.body = respAdapter(err, err, false);
    }
  }
}

module.exports = DataController;
